﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using SmartSpace;

namespace RTC.Web
{
    /// <summary>
    /// Summary description for RTCWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class RTCWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public ServiceResult SendMessage(string account, string content)
        {
            RTCService service = new RTCService();

            RTCMessage message = new RTCMessage();
            message.Id = Guid.NewGuid();
            message.Account = account;
            message.Content = content;
            message.Timestamp = DateTime.Now;
            if (service.Save(message))
            {
                return new ServiceResult(true, "ok");
            }
            return new ServiceResult(false, "failure");
        }

        [WebMethod]
        public ListResult<RTCMessage> GetMessage(string account)
        {
            DateTime timestamp = DateTime.Now;
            RTCService service = new RTCService();
            List<RTCMessage> messages = service.FindUnreceivedMessage(account);
            if (messages.Count > 0)
            {
                service.UpdateReceiveRecord(account, timestamp);
            }
            return new ListResult<RTCMessage>(messages);
        }

        [WebMethod]
        public ServiceResult Online(string account)
        {
            DateTime timestamp = DateTime.Now;
            RTCService service = new RTCService();
            if (service.ChangeUserState(account,true))
            {
                service.UpdateReceiveRecord(account, timestamp);
                return new ServiceResult(true, "ok");
            }
            return new ServiceResult(false, "failure");
        }

        [WebMethod]
        public ServiceResult Offline(string account)
        {
            RTCService service = new RTCService();
            if (service.ChangeUserState(account, false))
            {
                return new ServiceResult(true, "ok");
            }
            return new ServiceResult(false, "failure");
        }

        [WebMethod]
        public ListResult<RTCUser> GetOnlineUsers()
        {
            RTCService service = new RTCService();

            List<RTCUser> users = service.GetOnlineUsers();

            return new ListResult<RTCUser>(users);
        }
    }
}
